{
  "cells": [
    {
      "cell_type": "markdown",
      "id": "4a9a97e0",
      "metadata": {
        "id": "4a9a97e0"
      },
      "source": [
        "# APIs — Hands‑on with Python\n",
        "This Colab walks you through three live API calls:\n",
        "1. Weather forecast\n",
        "2. Cat facts\n",
        "3. OpenAI Chat Completions\n"
      ]
    },
    {
      "cell_type": "markdown",
      "source": [
        "## 📦 installation"
      ],
      "metadata": {
        "id": "gcZTDV5CBHrk"
      },
      "id": "gcZTDV5CBHrk"
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "fa969b2b",
      "metadata": {
        "id": "fa969b2b"
      },
      "outputs": [],
      "source": [
        "!pip -q install requests openai"
      ]
    },
    {
      "cell_type": "markdown",
      "source": [
        "# 📦 Imports"
      ],
      "metadata": {
        "id": "d1CPo0lHIwni"
      },
      "id": "d1CPo0lHIwni"
    },
    {
      "cell_type": "code",
      "execution_count": 32,
      "id": "7f5d5582",
      "metadata": {
        "id": "7f5d5582"
      },
      "outputs": [],
      "source": [
        "import requests, pprint\n",
        "\n"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "dca3b817",
      "metadata": {
        "id": "dca3b817"
      },
      "source": [
        "##  ⚙️ 1. Get current weather for London (Simple api call )"
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "url = \"https://api.open-meteo.com/v1/forecast?latitude=51.5&longitude=-0.12&current_weather=true\"\n",
        "resp = requests.get(url, timeout=10)\n",
        "resp.raise_for_status()\n",
        "weather = resp.json()\n",
        "pprint.pp(weather)"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "w36xxy0hI0Lh",
        "outputId": "cf445157-e793-4ae0-b2cc-506c6b56ef84"
      },
      "id": "w36xxy0hI0Lh",
      "execution_count": 33,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "{'latitude': 51.5,\n",
            " 'longitude': -0.120000124,\n",
            " 'generationtime_ms': 0.06592273712158203,\n",
            " 'utc_offset_seconds': 0,\n",
            " 'timezone': 'GMT',\n",
            " 'timezone_abbreviation': 'GMT',\n",
            " 'elevation': 1.0,\n",
            " 'current_weather_units': {'time': 'iso8601',\n",
            "                           'interval': 'seconds',\n",
            "                           'temperature': '°C',\n",
            "                           'windspeed': 'km/h',\n",
            "                           'winddirection': '°',\n",
            "                           'is_day': '',\n",
            "                           'weathercode': 'wmo code'},\n",
            " 'current_weather': {'time': '2025-07-20T14:15',\n",
            "                     'interval': 900,\n",
            "                     'temperature': 21.2,\n",
            "                     'windspeed': 15.2,\n",
            "                     'winddirection': 202,\n",
            "                     'is_day': 1,\n",
            "                     'weathercode': 3}}\n"
          ]
        }
      ]
    },
    {
      "cell_type": "markdown",
      "id": "43e226af",
      "metadata": {
        "id": "43e226af"
      },
      "source": [
        "## ⚙️ 2. Swap endpoint: Cat Fact"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 34,
      "id": "d1a75b24",
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "d1a75b24",
        "outputId": "ab89bce0-106e-492e-a7d1-f09a385bfd97"
      },
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "Mohammed loved cats and reportedly his favorite cat, Muezza, was a tabby. Legend says that tabby cats have an “M” for Mohammed on top of their heads because Mohammad would often rest his hand on the cat’s head.\n"
          ]
        }
      ],
      "source": [
        "url = \"https://catfact.ninja/fact\"\n",
        "resp = requests.get(url, timeout=10)\n",
        "resp.raise_for_status()\n",
        "print(resp.json()['fact'])"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "b531c0bf",
      "metadata": {
        "id": "b531c0bf"
      },
      "source": [
        "## 3. 🔐 Load API Key\n",
        "Fill in your API key below. You can store it in an environment variable or directly in the code (not recommended for production)."
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "from google.colab import userdata\n",
        "OPENAI_API_KEY = userdata.get('OPENAI_API_KEY')\n"
      ],
      "metadata": {
        "id": "LzAes2NNygH-"
      },
      "id": "LzAes2NNygH-",
      "execution_count": 35,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "## Checking Behavior - Stateless or Stateful"
      ],
      "metadata": {
        "id": "27Ie3wbFBel_"
      },
      "id": "27Ie3wbFBel_"
    },
    {
      "cell_type": "code",
      "execution_count": 36,
      "id": "2d2be137",
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "2d2be137",
        "outputId": "7e9ba965-bdda-4edd-dc76-d3dbffaa8d75"
      },
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "Hello, Wania! How are you today?\n"
          ]
        }
      ],
      "source": [
        "import os, openai\n",
        "\n",
        "# 🔑 TODO: Replace with your own key or set OPENAI_API_KEY in the environment\n",
        "openai.api_key = OPENAI_API_KEY\n",
        "\n",
        "response = openai.chat.completions.create(\n",
        "    model=\"gpt-4o-mini\",\n",
        "    messages=[{\"role\": \"user\", \"content\": \"Say hello! I'm Wania\"}]\n",
        ")\n",
        "print(response.choices[0].message.content)"
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "response = openai.chat.completions.create(\n",
        "    model=\"gpt-4o-mini\",\n",
        "    messages=[{\"role\": \"user\", \"content\": \"What's my name?\"}]\n",
        ")\n",
        "print(response.choices[0].message.content)"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "1FIPkwn9zd1i",
        "outputId": "6460d498-f61e-49c7-d4bb-ce75e2564f03"
      },
      "id": "1FIPkwn9zd1i",
      "execution_count": 37,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "I'm sorry, but I don't have access to that information. If you'd like, you can tell me your name!\n"
          ]
        }
      ]
    },
    {
      "cell_type": "markdown",
      "source": [
        "# Responses API\n"
      ],
      "metadata": {
        "id": "TTDSEFOEzmmp"
      },
      "id": "TTDSEFOEzmmp"
    },
    {
      "cell_type": "markdown",
      "source": [
        "## Checking Behavior - Stateless or Stateful"
      ],
      "metadata": {
        "id": "orQ1nnIvBwIe"
      },
      "id": "orQ1nnIvBwIe"
    },
    {
      "cell_type": "code",
      "source": [
        "from openai import OpenAI\n",
        "from google.colab import userdata\n",
        "\n",
        "OPENAI_API_KEY = userdata.get('OPENAI_API_KEY')\n",
        "client = OpenAI(api_key=OPENAI_API_KEY)\n",
        "\n",
        "response = client.responses.create(\n",
        "    model=\"gpt-4.1\",\n",
        "    input=[\n",
        "        {\n",
        "            \"role\": \"user\",\n",
        "            \"content\": [\n",
        "                { \"type\": \"input_text\", \"text\": \"what is in this image?\" },\n",
        "                {\n",
        "                    \"type\": \"input_image\",\n",
        "                    \"image_url\": \"https://upload.wikimedia.org/wikipedia/commons/thumb/d/dd/Gfp-wisconsin-madison-the-nature-boardwalk.jpg/2560px-Gfp-wisconsin-madison-the-nature-boardwalk.jpg\"\n",
        "                }\n",
        "            ]\n",
        "        }\n",
        "    ]\n",
        ")\n",
        "\n",
        "print(response.output[0].content[0].text)"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "QvbonFkyzj0A",
        "outputId": "8d3cd87a-d19e-49f0-82e1-992658b55932"
      },
      "id": "QvbonFkyzj0A",
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "This image shows a wooden boardwalk path running through a lush, green field or wetland area. The scene appears to be natural and tranquil, with tall grasses and vegetation on either side of the walkway. In the background, there are some trees and bushes. The sky is blue with some clouds, suggesting a pleasant, possibly late afternoon or early evening setting.\n"
          ]
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "from openai import OpenAI\n",
        "from google.colab import userdata\n",
        "\n",
        "OPENAI_API_KEY = userdata.get('OPENAI_API_KEY')\n",
        "client = OpenAI(api_key=OPENAI_API_KEY)\n",
        "\n",
        "response = client.responses.create(\n",
        "    model=\"gpt-4.1\",\n",
        "    store=True,\n",
        "    input=[\n",
        "        {\n",
        "            \"role\": \"user\",\n",
        "            \"content\": [\n",
        "                { \"type\": \"input_text\", \"text\": \"hello, I'm Wania\" },\n",
        "            ]\n",
        "        }\n",
        "    ]\n",
        ")\n",
        "\n",
        "print(response.output[0].content[0].text)"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "5ZyYfvcv0hbL",
        "outputId": "26859a2e-a3c5-478e-a8d8-87f3fd9d96f5"
      },
      "id": "5ZyYfvcv0hbL",
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "Hello, Wania! 👋 How can I help you today?\n"
          ]
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "next_response = client.responses.create(\n",
        "    model=\"gpt-4.1\",\n",
        "    store=True,\n",
        "    previous_response_id=response.id,  # 👈 linking to earlier message\n",
        "    input=[\n",
        "        {\n",
        "            \"role\": \"user\",\n",
        "            \"content\": [\n",
        "                { \"type\": \"input_text\", \"text\": \"What is my name?\" },\n",
        "            ]\n",
        "        }\n",
        "    ]\n",
        ")\n",
        "\n",
        "print(\"Follow-up response:\", next_response.output[0].content[0].text)\n"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "2oIgMo_k1xUe",
        "outputId": "5c291c85-7d85-4d16-febb-f3bb3b4938a2"
      },
      "id": "2oIgMo_k1xUe",
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "Follow-up response: Your name is Wania! 😊\n"
          ]
        }
      ]
    },
    {
      "cell_type": "markdown",
      "source": [
        "# 😊 Gemini Code"
      ],
      "metadata": {
        "id": "naMFaJHPFvJA"
      },
      "id": "naMFaJHPFvJA"
    },
    {
      "cell_type": "markdown",
      "source": [
        "# 📦 Imports"
      ],
      "metadata": {
        "id": "ZIA6rLuOEhj5"
      },
      "id": "ZIA6rLuOEhj5"
    },
    {
      "cell_type": "code",
      "source": [
        "from openai import OpenAI\n",
        "from google.colab import userdata"
      ],
      "metadata": {
        "id": "IwbuyW5wDlJa"
      },
      "id": "IwbuyW5wDlJa",
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "# 🔐 Load API Key"
      ],
      "metadata": {
        "id": "_p4GZAVmDv6Y"
      },
      "id": "_p4GZAVmDv6Y"
    },
    {
      "cell_type": "code",
      "source": [
        "api_key = userdata.get('GEMINI_API_KEY')"
      ],
      "metadata": {
        "id": "FpkOZ-w6D2hJ"
      },
      "id": "FpkOZ-w6D2hJ",
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "# 🤖 Initialize Gemini Client"
      ],
      "metadata": {
        "id": "rfJF3kT2EAtZ"
      },
      "id": "rfJF3kT2EAtZ"
    },
    {
      "cell_type": "code",
      "source": [
        "client = OpenAI(\n",
        "    api_key=api_key,\n",
        "    base_url=\"https://generativelanguage.googleapis.com/v1beta/openai/\"\n",
        ")"
      ],
      "metadata": {
        "id": "W42Ax6PKEDho"
      },
      "id": "W42Ax6PKEDho",
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "# 💬 Run Basic Chat Completion"
      ],
      "metadata": {
        "id": "9XmnFS-NEGrI"
      },
      "id": "9XmnFS-NEGrI"
    },
    {
      "cell_type": "code",
      "source": [
        "def main():\n",
        "    print(\"🧠 Asking Gemini a question...\\n\")\n",
        "\n",
        "    response = client.chat.completions.create(\n",
        "        model=\"gemini-2.5-flash\",\n",
        "        messages=[\n",
        "            {\"role\": \"system\", \"content\": \"You are a helpful assistant.\"},\n",
        "            {\"role\": \"user\",   \"content\": \"Explain how AI works in simple terms.\"}\n",
        "        ]\n",
        "    )\n",
        "\n",
        "    message = response.choices[0].message.content\n",
        "    print(\"💡 Gemini's Response:\\n\")\n",
        "    print(message)"
      ],
      "metadata": {
        "id": "TcM49HaSEJ3Q"
      },
      "id": "TcM49HaSEJ3Q",
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "# 🚀 Entry Point"
      ],
      "metadata": {
        "id": "qx0Lsqj5EUdg"
      },
      "id": "qx0Lsqj5EUdg"
    },
    {
      "cell_type": "code",
      "source": [
        "if __name__ == \"__main__\":\n",
        "    main()"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "-6PQQa55EOAZ",
        "outputId": "9f5df7a1-3956-42e8-eeaf-01022f791b24"
      },
      "id": "-6PQQa55EOAZ",
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "🧠 Asking Gemini a question...\n",
            "\n",
            "💡 Gemini's Response:\n",
            "\n",
            "Imagine you want to teach a computer to tell the difference between a cat and a dog.\n",
            "\n",
            "Here's how AI essentially works, simplified:\n",
            "\n",
            "1.  **Show and Tell (Training Data):**\n",
            "    You don't just tell the computer \"This is a cat.\" Instead, you show it *thousands* (or even millions) of pictures of cats, and for each one, you label it \"cat.\" You do the same with dogs, labeling them \"dog.\" This massive collection of labeled examples is called **training data**.\n",
            "\n",
            "2.  **Pattern Recognition (Learning Algorithms):**\n",
            "    The AI isn't like a human brain. It's more like a very powerful pattern-finding machine. It looks at all these pictures and starts to figure out what common features belong to cats (pointy ears, certain eye shapes, whiskers, etc.) and what belongs to dogs (floppy ears, different snout shapes, etc.). It builds its own internal \"rules\" or \"understanding\" based on these patterns. These \"rules\" are developed by **algorithms**, which are just very smart sets of instructions.\n",
            "\n",
            "3.  **Making a Guess (Prediction):**\n",
            "    Once the AI has \"learned\" from all the training data, you can show it a *brand-new picture* it's never seen before. Based on the patterns it found during training, it will make a guess: \"I think this is a cat\" or \"I think this is a dog.\" The more data it sees and the better its algorithms, the more accurate its guesses will be.\n",
            "\n",
            "**Think of it like this:**\n",
            "\n",
            "*   **Data:** Is the \"food\" the AI eats. The more diverse and relevant the food, the better it learns.\n",
            "*   **Algorithms:** Are the \"recipes\" or \"instruction manuals\" that tell the AI how to process that food and find patterns.\n",
            "*   **Learning:** Is the process of the AI adjusting its internal \"rules\" based on the data to get better at its task.\n",
            "\n",
            "**In essence, AI is about:**\n",
            "\n",
            "*   **Feeding computers vast amounts of data.**\n",
            "*   **Using clever programs (algorithms) to find patterns and relationships in that data.**\n",
            "*   **Allowing the computer to use those patterns to make predictions, decisions, or perform tasks without being explicitly programmed for every single scenario.**\n",
            "\n",
            "It's not \"thinking\" or \"conscious\" like a human, but it's incredibly good at finding complex patterns and acting on them.\n",
            "\n",
            "**Examples you might encounter:**\n",
            "\n",
            "*   **Siri or Alexa:** Trained on millions of voice recordings to recognize your words and understand commands.\n",
            "*   **Netflix recommendations:** Trained on your viewing history and what similar users watch to suggest new movies.\n",
            "*   **Self-driving cars:** Trained on countless hours of driving data, road signs, and object recognition to navigate.\n",
            "*   **Spam filters:** Trained on examples of spam and legitimate emails to identify unwanted messages.\n"
          ]
        }
      ]
    }
  ],
  "metadata": {
    "colab": {
      "provenance": []
    },
    "language_info": {
      "name": "python"
    },
    "kernelspec": {
      "name": "python3",
      "display_name": "Python 3"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 5
}